package com.feihong.txgw.ui.activity.product;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.adapter.base.BaseQuickAdapter;
import com.blankj.utilcode.util.KeyboardUtils;
import com.feihong.txgw.R;
import com.feihong.txgw.adapter.searchGoods.SearchStoreAndGoodsAdapter;
import com.feihong.txgw.inter.contract.product.IProSearchContract;
import com.feihong.txgw.message.LoginMessage;
import com.feihong.txgw.model.bean.searchList.SearchListEntity;
import com.feihong.txgw.model.bean.searchList.SearchPhoneListModel;
import com.feihong.txgw.tx_precenter.ProSearcMainPrecenter;
import com.feihong.txgw.ui.activity.Nearby.MenDianDetailActivity;
import com.feihong.txgw.ui.mvp.BaseMVPCompateActivity;
import com.feihong.txgw.ui.mvp.precenter.AbBasePrecenter;
import com.feihong.txgw.utils.HistoryUtil;
import com.feihong.txgw.utils.UserLoginInfo;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.feihong.txgw.ui.fragment.home.DiscoverFragment.INTENT_PRODUCTID;

/**
 * Created by Sabirjan on 2017/6/30.
 * TXGWApp.
 * 飞宏电子
 * 默认列表
 */

public class SearchActivity extends BaseMVPCompateActivity<IProSearchContract.AbProSearchMainPrecenter> implements View.OnClickListener, IProSearchContract.IProSearchMainView, BaseQuickAdapter.RequestLoadMoreListener {

    @BindView(R.id.et_search)
    EditText etInputCitys;
    @BindView(R.id.back)
    RelativeLayout back;
    @BindView(R.id.iv_etclear)
    ImageView clear;

    @BindView(R.id.search_list_swipRefresh_layout)
    SwipeRefreshLayout mRefreshLayout;
//    MaterialRefreshLayout mRefreshLayout;

    @BindView(R.id.search_recyclerView)
    RecyclerView mRecyclerView;
    @BindView(R.id.lay_loading)
    RelativeLayout mLoadLayout;
    private String longitude;
    private String latitude;
    private LinearLayoutManager linearLayoutManager;

    private String input;

    @BindView(R.id.search_no_layout)
    LinearLayout mSearchNoLayout;
    @BindView(R.id.connect_net_error_layout)
    LinearLayout mConnectErrorlayout;
    @BindView(R.id.re_query_data_layout)
    LinearLayout mRequeryDataLayout;
    @BindView(R.id.activity_hotsearch_status_layout)
    View mStatusLayout;
    private HistoryUtil mHistoryUtil;

    private boolean isHasData = false;
    private SearchStoreAndGoodsAdapter mSearchAdapter;
    private int mAllPageDataSize = 0;

    @Override
    public void setTheme() {

    }

    @Override
    public int setLayoutID() {
        return R.layout.activity_hotsearch;
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        mHistoryUtil = HistoryUtil.getInstance();
        Intent text = getIntent();
        input = text.getStringExtra("text");
        longitude = UserLoginInfo.getUserCityInfo().getLongitude();
        latitude = UserLoginInfo.getUserCityInfo().getLatitude();
        if (TextUtils.isEmpty(longitude) || TextUtils.isEmpty(latitude)) {
            latitude = UserLoginInfo.getUserCityInfo().getLatitude();
            longitude = UserLoginInfo.getUserCityInfo().getLongitude();
        }
        etInputCitys.setText(input);
        if (!TextUtils.isEmpty(etInputCitys.getText())) {
            clear.setVisibility(View.VISIBLE);
        }

        mRequeryDataLayout.setOnClickListener(this);
        linearLayoutManager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(linearLayoutManager);
        mRefreshLayout.setColorSchemeColors(Color.rgb(223, 47, 47));
        mRefreshLayout.setVisibility(View.GONE);
        mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mAllPageDataSize = 0;
                isHasData = false;
                mPresenter.getGoodsForFirst(latitude, longitude, input);
            }
        });
        initAdapter();
        setSpecificTitleLayout(mStatusLayout);
    }

    private void initAdapter() {
        mSearchAdapter = new SearchStoreAndGoodsAdapter(null);
        mSearchAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                SearchListEntity searchListEntity = (SearchListEntity) adapter.getItem(position);
                Intent intent = new Intent();
                if(searchListEntity.getItemType() == SearchListEntity.SEARCH_GOODS_TYPE){
                    intent.setClass(SearchActivity.this,ProductInfoActivity.class);
                    SearchPhoneListModel.DataBean.GoodsListBean goodsListBean = (SearchPhoneListModel.DataBean.GoodsListBean) searchListEntity;
                    intent.putExtra(INTENT_PRODUCTID,goodsListBean.getSku_id());
                }else {
                    intent.setClass(SearchActivity.this, MenDianDetailActivity.class);
                    SearchPhoneListModel.DataBean.StoreListBean storeListBean = (SearchPhoneListModel.DataBean.StoreListBean) searchListEntity;
                    intent.putExtra("store_id", storeListBean.getStore_id())
                            .putExtra("store_name", storeListBean.getStore_name());
                }
                startActivity(intent);
            }
        });
        mRecyclerView.setAdapter(mSearchAdapter);
    }

    @OnClick({R.id.back, R.id.iv_etclear})
    public void OnClick(View v) {
        switch (v.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.iv_etclear:
                etInputCitys.setText("");
                input = "";
                break;
            default:
                break;
        }
    }

    @Override
    public void bindData() {
        mPresenter.getGoodsForFirst(latitude, longitude, input);
        etInputCitys.addTextChangedListener(watcher);
        etInputCitys.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    input = etInputCitys.getText().toString().trim();
                    if (!TextUtils.isEmpty(input)) {
                        mHistoryUtil.setHistory(input);
                        getData();
                        KeyboardUtils.hideSoftInput(SearchActivity.this);
                    } else {
                        showSystemToast("请输入有效内容");
                    }
                }
                return false;
            }
        });
    }

    private TextWatcher watcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            clear.setVisibility(View.VISIBLE);
        }

        @Override
        public void afterTextChanged(Editable s) {
            clear.setVisibility(View.VISIBLE);
        }
    };

    @Override
    public void onUserLogin(LoginMessage loginMessage) {
    }

    public static final String goodsType = "p2";
    public static final String storeType = "p1";
    public static final int storeOnePageCount = 6;

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.re_query_data_layout:
                getData();
                mLoadLayout.setVisibility(View.VISIBLE);
                break;
            default:
                break;
        }
    }


    @Override
    public void getDataResult(List<SearchListEntity> searchListEntity,boolean isInterceptor) {
        mRefreshLayout.setVisibility(View.VISIBLE);
        mConnectErrorlayout.setVisibility(View.GONE);
        mSearchNoLayout.setVisibility(View.GONE);
        mAllPageDataSize += searchListEntity.size();
        if (!isHasData) {
            if (!isInterceptor) {
                mSearchAdapter.setOnLoadMoreListener(this, mRecyclerView);
            }
            isHasData = true;
            mSearchAdapter.setNewData(searchListEntity);
        }else {
            mSearchAdapter.addData(searchListEntity);
        }

        mSearchAdapter.loadMoreComplete();
    }

    @Override
    public void noData() {
        if (mAllPageDataSize != 0) {
            mSearchAdapter.loadMoreEnd();
        } else {
            mSearchNoLayout.setVisibility(View.VISIBLE);
            mConnectErrorlayout.setVisibility(View.GONE);
            mRefreshLayout.setVisibility(View.GONE);
        }

    }

    @Override
    public void loadDataComplated() {
        finishRefreshing();
    }

    @Override
    public void loadDataError() {
        finishRefreshing();
        if (mAllPageDataSize != 0) {
            mSearchAdapter.loadMoreFail();
            mSearchNoLayout.setVisibility(View.GONE);
            mConnectErrorlayout.setVisibility(View.GONE);
            mRefreshLayout.setVisibility(View.VISIBLE);
            showSystemToast(getResources().getString(R.string.connect_service_error));
        } else {
            mSearchNoLayout.setVisibility(View.GONE);
            mConnectErrorlayout.setVisibility(View.VISIBLE);
            mRefreshLayout.setVisibility(View.GONE);
        }
    }

    private void finishRefreshing() {
        if (mRefreshLayout.isRefreshing()) {
            mRefreshLayout.setRefreshing(false);
        }
        if (mLoadLayout.getVisibility() == View.VISIBLE) {
            mLoadLayout.setVisibility(View.GONE);
        }
    }

    @NonNull
    @Override
    public AbBasePrecenter initPresenter() {
        return ProSearcMainPrecenter.create();
    }

    @Override
    public void onLoadMoreRequested() {
        getData();
    }

    public void getData() {
        mPresenter.getGoodsData(latitude, longitude, input);
    }
}

